
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            width: 350px;
            height: 350px;
            margin: 100px;
            border: 1px solid #ccc;
            position: relative;
        }

        .big {
            width: 400px;
            height: 400px;
            position: absolute;
            top: 0;
            left: 360px;
            border: 1px solid #ccc;
            overflow: hidden;
            display: none;
        }

        .mask {
            width: 175px;
            height: 175px;
            background: rgba(255, 255, 0, 0.4);
            position: absolute;
            top: 0px;
            left: 0px;
            cursor: move;
            display: none;
        }

        .small {
            position: relative;
        }

    </style>
</head>
<body>
<div class="box" id="box">
    <div class="small">
        <img src="img/magnifier/small.webp" width="350" alt=""/>

        <div class="mask"></div>
    </div>

    <div class="big">
        <img src="img/magnifier/big.jpg" width="800" alt=""/>
    </div>
</div>
<script>
    //获取需要的dom对象
    var box = document.getElementById("box");
    var smallBox = box.children[0];
    //黄色的遮盖层
    var mask = smallBox.children[1];
    //
    var bigBox = box.children[1];
    var bigImg = bigBox.children[0];

    //1 鼠标放到smallBox。显示黄色的层
    smallBox.onmouseover = function () {
        bigBox.style.display = "block";
        mask.style.display = "block";
    }
    smallBox.onmouseout = function () {
        bigBox.style.display = "none";
        mask.style.display = "none";
    }

    //2 鼠标移动的时候，设置mask的位置
    smallBox.onmousemove = function (e) {
        //offsetWidth 可以获取到mask的宽度包括 边框和内边距
        var w = mask.offsetWidth/2;
        var h = mask.offsetHeight/2;

        //mask的坐标
        var x = e.clientX - 100 -w;
        var y = e.clientY - 100 -h;

        //控制mask不出去
        x = x < 0 ? 0 : x;
        y = y < 0 ? 0 : y;

        x = x > smallBox.offsetWidth - mask.offsetWidth ? smallBox.offsetWidth - mask.offsetWidth : x;
        y = y > smallBox.offsetHeight - mask.offsetHeight ? smallBox.offsetHeight - mask.offsetHeight:y;

        mask.style.left = x + "px";
        mask.style.top = y + "px";

        //3 改变大图片的位置
        // mask最大的移动距离/图片的最大移动距离  =  mask的移动距离/bigImg的移动距离
        //bigImg的移动距离= mask的移动距离  *  图片的最大移动距离 / mask最大的移动距离;
        var smallToMove = smallBox.offsetWidth - mask.offsetWidth;
        var bigToMove = bigImg.offsetWidth - bigBox.offsetWidth;

        var marginLeft = x * bigToMove / smallToMove;
        var marginTop = y * bigToMove / smallToMove;

        //
        bigImg.style.marginLeft = - marginLeft + "px";
        bigImg.style.marginTop = - marginTop + "px";
    }
</script>
</body>
</html>
